const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 7071 });
const clients = new Map();

function uuidv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}
console.log("wss up");

function makeDatas() {
    let i = 0;
    let newDatas = [];
    while (i < 1000) {
        i++;
        newDatas.push(Math.random());
    }
    return newDatas
}

wss.on('connection', (ws) => {
    const id = uuidv4();
    const color = Math.floor(Math.random() * 360);
    const metadata = { id, color };
    console.log('connection')

    clients.set(ws, metadata);


    ws.on('message', (messageAsString) => {
        console.log('message', messageAsString)
        // const message = JSON.parse(messageAsString);
        const metadata = clients.get(ws);

        // message.sender = metadata.id;
        // message.color = metadata.color;
        // const outbound = JSON.stringify(message);

        // [...clients.keys()].forEach((client) => {
        //     client.send(outbound);
        // });


        ws.send(JSON.stringify(makeDatas()));

        setInterval(() => {
            ws.send(JSON.stringify(makeDatas()));
        }, 1000);
    });
    ws.on("close", () => {
        clients.delete(ws);
    });
});
